﻿using System;
using System.Collections.Generic;
using Unread.App.ViewModels;
using Windows.Foundation;
using Windows.UI.Popups;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Unread.App.Views
{
    public sealed partial class ManageFeedsPage : Unread.App.Common.LayoutAwarePage
    {
        public ManageFeedsViewModel ViewModel
        {
            get
            {
                return DataContext as ManageFeedsViewModel;
            }
        }

        public ManageFeedsPage()
        {
            this.InitializeComponent();

            DataContext = ServicesFactory.GetInstance<ManageFeedsViewModel>();
        }

        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            await ViewModel.Load();
        }

        private void BottomAppBar_Loaded(object sender, RoutedEventArgs e)
        {
            RegisterAppBarButtons();
        }

        private void RegisterAppBarButtons()
        {
            Grid foo = BottomAppBar.Content as Grid;
            foreach (UIElement e in foo.Children)
            {
                foreach (UIElement c in ((StackPanel)e).Children)
                {
                    if (c.GetType() == typeof(Button))
                    {
                        base.StartLayoutUpdates(c, new RoutedEventArgs());
                    }
                }
            }
        }

        private void itemListView_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            if (ViewModel.OpenFeedCommand.CanExecute(null))
                ViewModel.OpenFeedCommand.Execute(null);
        }

        private async void Pin_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            var logo = new Uri("ms-appx:///Assets/Logo.png");
            var tileActivationArguments = "feed";

            var secondaryTile = new SecondaryTile(ViewModel.SelectedFeed.Id.ToString(),
                ViewModel.SelectedFeed.Title, ViewModel.SelectedFeed.Title, tileActivationArguments, TileOptions.ShowNameOnLogo, logo);
            secondaryTile.ForegroundText = ForegroundText.Dark;

            await secondaryTile.RequestCreateForSelectionAsync(GetElementRect((FrameworkElement)sender), Placement.Below);
        }

        private Rect GetElementRect(FrameworkElement element)
        {
            var buttonTransform = element.TransformToVisual(null);
            var point = buttonTransform.TransformPoint(new Point());

            return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
        }
    }
}
